﻿using System;
using System.Reflection;


namespace SL.MVVMS.RIA
{
    /// <summary>
    /// this provides ability to use Weak References when Attaching Events to
    /// the Notification Listener.  Adapted from Paul Stovell's blog at
    /// http://csharpfeeds.com/post/13688/WeakReference_Event_Handlers.aspx
    /// </summary>
    /// <typeparam name="TEventArgs"></typeparam>
    public sealed class WeakEventHandler<TEventArgs> where TEventArgs : EventArgs
    {
        private readonly WeakReference _targetReference;
        private readonly MethodInfo _method;

        public WeakEventHandler(NotificationEventHandler<TEventArgs> callback)
        {
            _method = callback.Method;
            _targetReference = new WeakReference(callback.Target, true);
        }

        public void Handler(object sender, TEventArgs e)
        {
            var target = _targetReference.Target;
            if (target != null)
            {
                var callback = (Action<object, TEventArgs>)Delegate.CreateDelegate(typeof(Action<object, TEventArgs>), target, _method, true);
                if (callback != null)
                {
                    callback(sender, e);
                }
            }
        }
    }

}
